
/* istanbul ignore next */
process.on('uncaughtException', function (err) {

    // Handle the error safely 
    console.log(err.message);
    console.log(err.stack);
    process.exit(1);
})

/* istanbul ignore next */
process.on('unhandledRejection', function (err) {

    // Handle the error safely 
    console.log(err)
    process.exit(1);
})

import express, { Request, Response } from "express";
import cors from "cors";
import { authLoginRouter } from "./routers/auth-login";
import { authRegRouter } from "./routers/auth-reg";
import { businessRouter } from "./routers/business";
import { authenticateToken } from "./services/auth";

// Create a new express application instance
const app = express();

// Set the network port
const port = process.env.PORT || 3000;

app.use(express.json({ limit: '50mb' }))
    .use(express.urlencoded({ extended: false }));

    app.use(cors());

// Define the root path with a greeting message
app.get("/", (req: Request, res: Response) => {
    res.json({ message: "Welcome to the Express + TypeScript Server!" });
});

const handleError = async (err, req, res, next) => {
    console.error(`${new Date()} error: `, err);
    let statusCode = err.statusCode ? err.statusCode : 500;
    let errorObj = {
        errorCode: err.errorCode ? err.errorCode : "UNKNOWN_ERROR",
        errorMsg: err.message ? err.message : "服务器端未知错误。",
        data: err.data
    };
    return res.status(statusCode).json(errorObj);
}

  app.use("/api/business/public",businessRouter);
  app.use("/api/auth/login", authLoginRouter);
  app.use("/api/auth/reg",authenticateToken, authRegRouter);

app.use(handleError);

// Start the Express server
app.listen(port, () => {
    console.log(`The server is running at http://localhost:${port}`);
});